package com.leyou.item.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.vo.PageResult;
import com.leyou.item.dto.*;
import com.leyou.item.entity.Sku;
import com.leyou.item.entity.Spu;
import com.leyou.item.entity.SpuDetail;
import com.leyou.item.mapper.SkuMapper;
import com.leyou.item.mapper.SpuDetailMapper;
import com.leyou.item.mapper.SpuMapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.leyou.common.constants.MQConstants.Exchange.ITEM_EXCHANGE_NAME;
import static com.leyou.common.constants.MQConstants.RoutingKey.ITEM_DOWN_KEY;
import static com.leyou.common.constants.MQConstants.RoutingKey.ITEM_UP_KEY;

@Service
public class GoodsService {
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private BrandService brandService;
    @Autowired
    private SpuMapper spuMapper;
    @Autowired
    private SpuDetailMapper spuDetailMapper;
    @Autowired
    private SkuMapper skuMapper;
    @Autowired
    AmqpTemplate amqpTemplate;


    public PageResult<SpuDTO> querySpuByPage(String key, Integer page, Integer rows, Boolean saleable) {
        //分页设置
        PageHelper.startPage(page,rows);
        //条件过滤
        Example example = new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();
        //判断关键字
        if (StringUtils.isNotBlank(key)){
            criteria.andLike("name","%" + key + "%");
        }
        //判断是否上下架
        if (saleable != null){
            criteria.andEqualTo("saleable",saleable);
        }
        //根据更新时间排序条件
        example.setOrderByClause("update_time DESC");
        //查询
        List<Spu> spuList = spuMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(spuList)){
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }

        //总记录数
        PageInfo<Spu> spuPageInfo = new PageInfo<>(spuList);
        long total = spuPageInfo.getTotal();
        //当前页数据
        List<Spu> list = spuPageInfo.getList();
        List<SpuDTO> spuDTOList = BeanHelper.copyWithCollection(list, SpuDTO.class);

        //处理分类名称和品牌名称
        handleCategoryAndBrandName(spuDTOList);

        //封装成DTO对象
        return new PageResult<>(spuDTOList,total);
    }

    //处理分类名称和品牌名称
    private void handleCategoryAndBrandName(List<SpuDTO> spuDTOList) {
        for (SpuDTO spuDTO : spuDTOList) {
            //处理品牌名称
            Long brandId = spuDTO.getBrandId();
            BrandDTO brandDTO = brandService.queryBrandById(brandId);
            spuDTO.setBrandName(brandDTO.getName());

            //处理分类名称
            List<Long> categoryIds = spuDTO.getCategoryIds();
            //批量查询分类
            List<CategoryDTO> categoryDTOList = categoryService.queryCategoryListByIds(categoryIds);

            //方式一(字符串拼接)
            /*
            StringBuilder sb = new StringBuilder();
            for (CategoryDTO cd : categoryDTOList) {
                sb.append(cd.getName()).append("/");
            }
            sb.substring(0,sb.toString().length() - 1);
            */
            //方式二(流方式)
            String categoryName = categoryDTOList.stream().map(CategoryDTO::getName).collect(Collectors.joining("/"));
            spuDTO.setCategoryName(categoryName);
        }
    }

    /**
     * 保存商品信息
     * @param spuDTO
     */
    @Transactional
    public void saveGoods(SpuDTO spuDTO) {
        //把DTO转成po
        Spu spu = BeanHelper.copyProperties(spuDTO, Spu.class);
        //保存spu
        int count = spuMapper.insertSelective(spu);
        if (count != 1){
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }
        //获取spu的id
        Long spuId = spu.getId();

        //保存spuDetail
        SpuDetailDTO spuDetailDTO = spuDTO.getSpuDetail();
        //把DTO转成po
        SpuDetail spuDetail = BeanHelper.copyProperties(spuDetailDTO, SpuDetail.class);
        spuDetail.setSpuId(spuId);
        count = spuDetailMapper.insertSelective(spuDetail);
        if (count != 1){
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }

        //保存sku集合
        List<SkuDTO> skuDTOList = spuDTO.getSkus();
        //把DTO转成po
        List<Sku> skuList = BeanHelper.copyWithCollection(skuDTOList, Sku.class);
        skuList.forEach(sku -> {
            sku.setSpuId(spuId);
        });

        //批量插入
        count = skuMapper.insertList(skuList);
        if (count != skuList.size()){
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }

    }

    /**
     * 修改商品上下架操作
     * @param spuId    商品id
     * @param saleable  商品上下架标志符
     */
    @Transactional
    public void updateSaleable(Long spuId, Boolean saleable) {
        //1.封装条件(更新spu)
        Spu spu = new Spu();
        spu.setId(spuId);
        spu.setSaleable(saleable);
        //2.更新spu
        int count = spuMapper.updateByPrimaryKeySelective(spu);
        if (count != 1){
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }
        //3.更新sku
        Sku sku = new Sku();
        sku.setEnable(saleable);
        Example example = new Example(Sku.class);
        example.createCriteria().andEqualTo("spuId",spuId);
        count = skuMapper.updateByExampleSelective(sku,example);
        if (count < 1){
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }

        //3.上下架操作, 发送消息队列: 1.静态化服务 2.搜索微服务
        amqpTemplate.convertAndSend(ITEM_EXCHANGE_NAME,(saleable ? ITEM_UP_KEY : ITEM_DOWN_KEY),spuId);
    }

    /**
     * 根据spuId查询spu信息
     * @param spuId
     * @return
     */
    public SpuDetailDTO querySpuDetailBySpuId(Long spuId) {
        SpuDetail spuDetail = spuDetailMapper.selectByPrimaryKey(spuId);
        if (spuDetail == null){
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        return BeanHelper.copyProperties(spuDetail,SpuDetailDTO.class);
    }

    /**
     * 查询sku集合
     * @param spuId
     * @return
     */
    public List<SkuDTO> querySkuListBySpuId(Long spuId) {
        Sku sku = new Sku();
        sku.setSpuId(spuId);
        List<Sku> skuList = skuMapper.select(sku);
        if (CollectionUtils.isEmpty(skuList)){
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(skuList,SkuDTO.class);
    }

    /**
     * 更新商品数据
     * @param spuDTO
     */
    @Transactional
    public void updateGoods(SpuDTO spuDTO) {
        //1.删除sku
        Long spuId = spuDTO.getId();
        if (spuId == null){
            throw new LyException(ExceptionEnum.INVALID_PARAM_ERROR);
        }
        Sku sku = new Sku();
        sku.setSpuId(spuId);

        int count = skuMapper.selectCount(sku);
        if (count > 0){
            int delete = skuMapper.delete(sku);
            if (count != delete){
                throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
            }
        }
        //2.更新spu
        Spu spu = BeanHelper.copyProperties(spuDTO, Spu.class);
        spu.setSaleable(null);
        spu.setUpdateTime(null);
        spu.setCreateTime(null);
        count = spuMapper.updateByPrimaryKeySelective(spu);     //通用Mapper凡是带有Selective,只会更新非空数据
        if (count != 1){
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }

        //3.更新spuDetail
        SpuDetail spuDetail = BeanHelper.copyProperties(spuDTO.getSpuDetail(), SpuDetail.class);
        spuDetail.setSpuId(spuId);
        count = spuDetailMapper.updateByPrimaryKeySelective(spuDetail);
        if (count != 1){
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }

        //4.批量插入sku集合
        //保存sku集合
        List<SkuDTO> skuDTOList = spuDTO.getSkus();
        //把DTO转成po
        List<Sku> skuList = BeanHelper.copyWithCollection(skuDTOList, Sku.class);
        skuList.forEach(s -> {
            s.setSpuId(spuId);
        });

        //批量插入
        count = skuMapper.insertList(skuList);
        if (count != skuList.size()){
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }
    }

    /**
     * 根据spuid查询spu
     * @param id    spuId
     * @return      spu
     */
    public SpuDTO querySpuById(Long id) {
        Spu spu = spuMapper.selectByPrimaryKey(id);
        if (spu == null){
            throw new LyException(ExceptionEnum.INVALID_PARAM_ERROR);
        }
        return BeanHelper.copyProperties(spu,SpuDTO.class);
    }

    /**
     * 根据skuIds批量查询skuDTO
     * @param ids   skuId的集合
     * @return  sku集合
     */
    public List<SkuDTO> querySkuByIds(List<Long> ids) {
        //查询sku
        List<Sku> skuList = skuMapper.selectByIdList(ids);
        if (CollectionUtils.isEmpty(skuList)){
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(skuList,SkuDTO.class);
    }

    /**
     * 减库存
     * @param cartMap   商品id及数量 Map
     * @return
     */
    @Transactional
    public void minusStock(Map<Long, Integer> cartMap) {
        for (Map.Entry<Long, Integer> entry : cartMap.entrySet()) {
            Long skuId = entry.getKey();
            Integer num = entry.getValue();
            int count = skuMapper.minusStock(skuId,num);
            if (count != 1){
                throw new RuntimeException("库存不足");
            }
        }
    }
}
